"""
用户模型
"""
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils.crypto import get_random_string
from django.utils import timezone
from datetime import timedelta


class User(AbstractUser):
    """用户模型（扩展Django默认用户）"""
    phone = models.CharField(max_length=20, verbose_name='手机号', blank=True, null=True)
    avatar = models.ImageField(upload_to='avatars/', verbose_name='头像', blank=True, null=True)
    preferences = models.JSONField(default=dict, verbose_name='用户偏好设置', blank=True)
    email_verified = models.BooleanField(default=False, verbose_name='邮箱已验证')
    phone_verified = models.BooleanField(default=False, verbose_name='手机已验证')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'users'
        verbose_name = '用户'
        verbose_name_plural = '用户'

    def __str__(self):
        return self.username


class EmailVerification(models.Model):
    """邮箱验证"""
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='email_verifications',
        verbose_name='用户'
    )
    email = models.EmailField(verbose_name='邮箱地址')
    verification_code = models.CharField(max_length=6, verbose_name='验证码')
    is_verified = models.BooleanField(default=False, verbose_name='是否已验证')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    expires_at = models.DateTimeField(verbose_name='过期时间')

    class Meta:
        db_table = 'email_verifications'
        verbose_name = '邮箱验证'
        verbose_name_plural = '邮箱验证'
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['email', 'verification_code']),
            models.Index(fields=['user', '-created_at']),
        ]

    def __str__(self):
        return f"{self.user.username} - {self.email}"

    def is_expired(self):
        """检查验证码是否过期"""
        return timezone.now() > self.expires_at

    def save(self, *args, **kwargs):
        """保存时自动设置过期时间（10分钟）"""
        if not self.expires_at:
            self.expires_at = timezone.now() + timedelta(minutes=10)
        super().save(*args, **kwargs)


class PhoneVerification(models.Model):
    """手机验证码"""
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='phone_verifications',
        verbose_name='用户'
    )
    phone = models.CharField(max_length=20, verbose_name='手机号')
    verification_code = models.CharField(max_length=6, verbose_name='验证码')
    is_verified = models.BooleanField(default=False, verbose_name='是否已验证')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    expires_at = models.DateTimeField(verbose_name='过期时间')

    class Meta:
        db_table = 'phone_verifications'
        verbose_name = '手机验证'
        verbose_name_plural = '手机验证'
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['phone', 'verification_code']),
            models.Index(fields=['user', '-created_at']),
        ]

    def __str__(self):
        return f"{self.user.username} - {self.phone}"

    def is_expired(self):
        """检查验证码是否过期"""
        return timezone.now() > self.expires_at

    def save(self, *args, **kwargs):
        """保存时自动设置过期时间（5分钟）"""
        if not self.expires_at:
            self.expires_at = timezone.now() + timedelta(minutes=5)
        super().save(*args, **kwargs)


class UserFollow(models.Model):
    """用户关注关系"""
    follower = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='following',
        verbose_name='关注者'
    )
    following = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='followers',
        verbose_name='被关注者'
    )
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='关注时间')

    class Meta:
        db_table = 'user_follows'
        verbose_name = '用户关注'
        verbose_name_plural = '用户关注'
        unique_together = ('follower', 'following')
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.follower.username} 关注 {self.following.username}"


class AdminActionLog(models.Model):
    """管理员操作日志"""
    ACTION_CHOICES = [
        ('create', '创建'),
        ('update', '更新'),
        ('delete', '删除'),
        ('export', '导出'),
        ('import', '导入'),
        ('toggle', '切换状态'),
        ('approve', '审核'),
        ('reject', '拒绝'),
        ('other', '其他'),
    ]
    
    admin = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='action_logs',
        verbose_name='管理员'
    )
    action = models.CharField(max_length=20, choices=ACTION_CHOICES, verbose_name='操作类型')
    target_type = models.CharField(max_length=50, verbose_name='目标类型')  # 如：景点、用户、动态
    target_id = models.IntegerField(null=True, blank=True, verbose_name='目标ID')
    target_name = models.CharField(max_length=200, blank=True, verbose_name='目标名称')
    description = models.TextField(blank=True, verbose_name='操作描述')
    ip_address = models.GenericIPAddressField(null=True, blank=True, verbose_name='IP地址')
    user_agent = models.CharField(max_length=500, blank=True, verbose_name='用户代理')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='操作时间')

    class Meta:
        db_table = 'admin_action_logs'
        verbose_name = '管理员操作日志'
        verbose_name_plural = '管理员操作日志'
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['admin', '-created_at']),
            models.Index(fields=['target_type', 'target_id']),
            models.Index(fields=['-created_at']),
        ]

    def __str__(self):
        return f"{self.admin.username} - {self.get_action_display()} - {self.target_type}"
